package fun.eliauk.shuatiba.job.once;


import cn.hutool.core.collection.CollUtil;
import fun.eliauk.shuatiba.esdao.QuestionEsDao;
import fun.eliauk.shuatiba.model.dto.question.QuestionEsDTO;
import fun.eliauk.shuatiba.model.entity.Question;
import fun.eliauk.shuatiba.service.QuestionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class FullSyncQuestionToEs implements CommandLineRunner {

    @Resource
    private QuestionService questionService;

    @Resource
    private QuestionEsDao questionEsDao;

    @Override
    public void run(String... args) throws Exception {
        List<Question> questionList = questionService.list();
        if (CollUtil.isEmpty(questionList)) {
            return;
        }

        // 转为 es 实体
        List<QuestionEsDTO> list = questionList.stream()
                .map(QuestionEsDTO::objToDto)
                .collect(Collectors.toList());

        // 分页批量插入 ES
        final int pageSize = 100;
        int total = list.size();
        log.info("FullSyncQuestionToEs start, total {}", total);
        for (int i = 0; i <= total; i += pageSize) {
            int end = Math.min(total, i + pageSize);
            log.info("sync from {} to {}", i, end);
            questionEsDao.saveAll(list.subList(i, end));
        }
        log.info("IncSyncQuestionToEs end, total {}", total);
    }
}
